{% extends 'base.html' %}
{% load static %}

{% block title %}{{ page_title }}{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card shadow-sm">
                <div class="card-body">
                    <!-- 返回按钮 -->
                    <a href="{% url 'location:reward_mall' %}" class="btn btn-outline-secondary mb-4">
                        <i class="fas fa-arrow-left me-2"></i>返回商城
                    </a>

                    <div class="row">
                        <!-- 商品图片 -->
                        <div class="col-md-5 mb-4">
                            {% if reward.image %}
                            <img src="{{ reward.image.url }}" alt="{{ reward.name }}" 
                                 class="img-fluid rounded shadow">
                            {% else %}
                            <div class="bg-light rounded d-flex align-items-center justify-content-center" 
                                 style="height: 300px;">
                                <i class="fas fa-gift fa-5x text-muted"></i>
                            </div>
                            {% endif %}
                        </div>

                        <!-- 商品信息 -->
                        <div class="col-md-7">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <h2 class="mb-0">{{ reward.name }}</h2>
                                <span class="badge 
                                    {% if reward.reward_type == 'coupon' %}bg-warning
                                    {% elif reward.reward_type == 'privilege' %}bg-info
                                    {% else %}bg-success{% endif %} fs-6">
                                    {% if reward.reward_type == 'coupon' %}优惠券
                                    {% elif reward.reward_type == 'privilege' %}特权
                                    {% else %}实物奖励{% endif %}
                                </span>
                            </div>

                            <p class="text-muted mb-4">{{ reward.description }}</p>

                            <!-- 积分信息 -->
                            <div class="card bg-light mb-4">
                                <div class="card-body">
                                    <div class="row text-center">
                                        <div class="col-6 border-end">
                                            <div class="h4 text-primary mb-1">{{ reward.points_required }}</div>
                                            <small class="text-muted">所需积分</small>
                                        </div>
                                        <div class="col-6">
                                            <div class="h4 
                                                {% if user_points >= reward.points_required %}text-success{% else %}text-danger{% endif %} mb-1">
                                                {{ user_points }}
                                            </div>
                                            <small class="text-muted">您的积分</small>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 库存信息 -->
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <span class="text-muted">
                                    <i class="fas fa-box me-1"></i>
                                    库存: {{ reward.stock_quantity }} 件
                                </span>
                                {% if not can_redeem %}
                                <span class="badge bg-danger">{{ redemption_message }}</span>
                                {% endif %}
                            </div>

                            <!-- 兑换按钮 -->
                            {% if can_redeem %}
                            <form id="redeemForm" method="post" action="{% url 'location:redeem_reward' reward.id %}">
                                {% csrf_token %}
                                <button type="submit" class="btn btn-primary btn-lg w-100 py-3">
                                    <i class="fas fa-shopping-cart me-2"></i>
                                    立即兑换
                                </button>
                            </form>
                            {% else %}
                            <button class="btn btn-secondary btn-lg w-100 py-3" disabled>
                                <i class="fas fa-times me-2"></i>
                                无法兑换
                            </button>
                            {% endif %}

                            <!-- 温馨提示 -->
                            <div class="alert alert-info mt-4">
                                <h6><i class="fas fa-info-circle me-2"></i>兑换说明</h6>
                                <ul class="mb-0 small">
                                    <li>兑换成功后积分将立即扣除</li>
                                    <li>实物商品将在3-5个工作日内发货</li>
                                    <li>虚拟商品将在24小时内发放</li>
                                    <li>如有问题请联系客服</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 获取 CSRF token 的函数
function getCsrfToken() {
    const name = 'csrftoken';
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 显示提示消息的函数
function showAlert(message, type) {
    // 移除现有的提示消息
    const existingAlert = document.querySelector('.custom-alert');
    if (existingAlert) {
        existingAlert.remove();
    }

    // 创建新的提示消息
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} custom-alert position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 1050; min-width: 300px;';
    alertDiv.innerHTML = `
        <div class="d-flex justify-content-between align-items-center">
            <span>${message}</span>
            <button type="button" class="btn-close" onclick="this.parentElement.parentElement.remove()"></button>
        </div>
    `;

    document.body.appendChild(alertDiv);

    // 3秒后自动消失
    setTimeout(() => {
        if (alertDiv.parentElement) {
            alertDiv.remove();
        }
    }, 3000);
}

document.addEventListener('DOMContentLoaded', function() {
    const redeemForm = document.getElementById('redeemForm');
    if (redeemForm) {
        redeemForm.addEventListener('submit', function(e) {
            e.preventDefault();

            if (!confirm(`确定要兑换「{{ reward.name }}」吗？将消耗 {{ reward.points_required }} 积分。`)) {
                return;
            }

            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>兑换中...';
            submitBtn.disabled = true;

            const formData = new FormData(this);

            fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCsrfToken(),
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络请求失败，状态码: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                console.log('兑换响应:', data); // 调试信息
                if (data.success) {
                    showAlert('✅ ' + data.message, 'success');
                    setTimeout(() => {
                        window.location.href = "{% url 'location:redemption_history' %}";
                    }, 1500);
                } else {
                    showAlert('❌ ' + data.message, 'error');
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                }
            })
            .catch(error => {
                console.error('兑换失败:', error);
                showAlert('❌ 网络错误，请重试: ' + error.message, 'error');
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        });
    }
});
</script>

<style>
.custom-alert {
    animation: slideIn 0.3s ease-out;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

@keyframes slideIn {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}
</style>
{% endblock %}